<template>
  <el-card>
    <h2>活动列表</h2>
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form" style="margin-bottom: 20px;">
      <el-form-item label="活动名称">
        <el-input v-model="searchForm.name" placeholder="请输入活动名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
          <el-option label="草稿" value="DRAFT" />
          <el-option label="待审核" value="PENDING" />
          <el-option label="通过C" value="APPROVED_C" />
          <el-option label="通过B" value="APPROVED_B" />
          <el-option label="通过" value="APPROVED" />
          <el-option label="驳回" value="REJECTED" />
          <el-option label="已完成" value="COMPLETED" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间区间">
        <el-date-picker
          v-model="searchForm.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DDTHH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="activities" style="width: 100%">
      <el-table-column prop="actId" label="活动ID" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="location" label="地点" />
      <el-table-column prop="startTime" label="开始时间" />
      <el-table-column prop="endTime" label="结束时间" />
      <el-table-column prop="point" label="分数" />
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button size="small" @click="editActivity(scope.row)">编辑</el-button>
          <el-button size="small" type="success" @click="submitActivity(scope.row)"
            :disabled="scope.row.status !== 'DRAFT'">提交</el-button>
          <el-button size="small" type="danger" @click="deleteActivity(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const activities = ref([])

const orgId = localStorage.getItem('loginId')

// 搜索表单数据
const searchForm = ref({
  name: '',
  status: '',
  timeRange: []
})

// 默认加载全部活动
const fetchAllActivities = async () => {
  try {
    const res = await axios.get(`http://localhost:8080/orgs/${orgId}/activities`)
    activities.value = res.data.data || [];
    console.log('活动列表:', activities.value);
  } catch (e) {
    ElMessage.error('获取活动列表失败')
  }
}

onMounted(fetchAllActivities)

// 搜索功能
const handleSearch = async () => {
  // 按活动名称
  activities.value = []; // 搜索前清空
  // 按活动名称
  if (searchForm.value.name) {
    try {
      const res = await axios.get(`http://localhost:8080/orgs/activities/${searchForm.value.name}`)
      activities.value = res.data.data || [];
      return
    } catch (e) {
      ElMessage.error('按关键字查询失败')
    }
  }
  // 按状态
  if (searchForm.value.status) {
    try {
      const res = await axios.get(`http://localhost:8080/orgs/activities/status/${searchForm.value.status}/${orgId}`)
      activities.value = res.data.data || [];
      console.log('按状态查询结果:', activities.value);
      return
    } catch (e) {
      ElMessage.error('按状态查询失败')
    }
  }
  // 按时间区间
  if (searchForm.value.timeRange.length === 2) {
    const [start, end] = searchForm.value.timeRange
    try {
      const res = await axios.get(`http://localhost:8080/orgs/activities/${start}/${end}/${orgId}`)
      activities.value = res.data.data || []
      return
    } catch (e) {
      ElMessage.error('按时间区间查询失败')
    }
  }
  // 如果都没填，加载全部
  fetchAllActivities()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    status: '',
    timeRange: []
  }
  fetchAllActivities()
}

// 下面是你的原有操作
const editActivity = (row) => {
  router.push({ path: `/activity/edit/${row.actId}` })
}

const submitActivity = async (row) => {
  try {
    // 新接口：orgId为路径参数，body只传activityId
    console.log('提交活动:', row.actId, orgId);
    const res = await axios.post(
      `http://localhost:8080/orgs/activities/submit/${orgId}`,
      { "id": row.actId }
    );
    if (res.data && res.data.code === 200) {
      ElMessage.success('已提交审核');
      row.status = 'PENDING'; // 状态大写
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '提交失败');
    }
  } catch (e) {
    ElMessage.error('提交失败');
  }
}

const deleteActivity = (row) => {
  ElMessageBox.confirm('确定要删除该活动吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await axios.delete(`http://localhost:8080/orgs/deleteActivities/${row.actId}/${orgId}`);
      if (res.data && res.data.code === 200) {
        ElMessage.success('删除成功');
        const idx = activities.value.findIndex(act => act.actId === row.actId);
        if (idx !== -1) activities.value.splice(idx, 1);
      } else {
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '删除失败1');
      }
    } catch (e) {
      ElMessage.error('删除失败');
    }
  });
}
</script>